package cn.wd.service.impl;

import cn.wd.domain.User;
import cn.wd.mapper.UserMapper;
import cn.wd.qo.PageResult;
import cn.wd.qo.QueryObject;
import cn.wd.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void delete(Long id) {
        userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(User user) {
        userMapper.insert(user);
    }

    @Override
    public User getById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    @Override
    public void update(User user) {
        userMapper.updateByPrimaryKey(user);
    }

    @Override
    public PageResult<User> query(QueryObject qo) {
        Long count = 0L;
        List<User> users = new ArrayList<>();

        if (qo.getInitKeyword() != null) {
            User user = userMapper.selectUserByUsername(qo.getInitKeyword());
            if (user != null && !user.getAdmin()) {
                count = 1L;
                users.add(user);
            } else {
                count = userMapper.selectForCount(qo);
                if (count == 0L){
                    return PageResult.empty(qo.getCurrent(), qo.getPageSize());
                }
                // List<User> userlist = userMapper;
                users = userMapper.selectForList(qo);
            }
        } else {
            count = userMapper.selectForCount(qo);
            if (count == 0L){
                return PageResult.empty(qo.getCurrent(), qo.getPageSize());
            }
            // List<User> userlist = userMapper;
            users = userMapper.selectForList(qo);
        }

        return new PageResult<>(qo.getCurrent(),qo.getPageSize(), count, users);
    }

    @Override
    public User login(User user) throws Exception {
        User userInDB = userMapper.selectUserByUsername(user.getUsername());
        if (userInDB == null || !user.getPassword().equals(userInDB.getPassword())) {
            throw new Exception("用户名或密码错误");
        }
        return userInDB;
    }

    @Override
    public void register(User user) throws Exception {
        User searchUser = userMapper.selectUserByUsername(user.getUsername());
        if (searchUser != null) {
            throw new Exception("用户名已存在");
        }
        user.setAdmin(false);
        user.setSex(2);
        user.setAge(18);
        userMapper.insert(user);
    }
}
